package com.huwaiwai.sort;

/**
 * 冒泡排序实现
 * Created by hww on 2018/12/6 10:29 PM.
 */
public class BubbleSort {

    public static void bubbleSortV1(int[] disorderedList) {
        int length = disorderedList.length;
        for (int j = 0; j < length - 1; j++) {
            for (int i = 0; i < length - 1; i++) {
                if (needExchange(disorderedList[i], disorderedList[i + 1])) {
                    int temp = disorderedList[i];
                    disorderedList[i] = disorderedList[i + 1];
                    disorderedList[i + 1] = temp;
                }
            }
        }
    }
    public static void bubbleSortV2(int[] disorderedList) {
        int length = disorderedList.length;
        for (int j = 0; j < length - 1; j++) {
            for (int i = 0; i < length - 1 - j; i++) {
                if (needExchange(disorderedList[i], disorderedList[i + 1])) {
                    int temp = disorderedList[i];
                    disorderedList[i] = disorderedList[i + 1];
                    disorderedList[i + 1] = temp;
                }
            }
        }
    }
    public static void bubbleSortV3(int[] disorderedList) {
        int length = disorderedList.length;
        for (int j = 0; j < length - 1; j++) {
            boolean a = false;
            for (int i = 0; i < length - 1 - j; i++) {
                if (needExchange(disorderedList[i], disorderedList[i + 1])) {
                    int temp = disorderedList[i];
                    disorderedList[i] = disorderedList[i + 1];
                    disorderedList[i + 1] = temp;
                    a = true;
                }
            }
            if (!a) {
                break;
            }
        }
    }
    private static boolean needExchange(int i, int j) {
        return i > j;
    }

}
